/**
 * @author dnguyen
 */
package climspace.client;


import java.util.Properties;

import javax.naming.Context;
import javax.naming.InitialContext;
import javax.rmi.PortableRemoteObject;

import climspace.ejb.DBJobTimer;

public class ClimSpaceAdminClient {

	private Context ctx;
	private DBJobTimer svc;
	private String host = "localhost";

	public void setHost(String host) {
		this.host = host;
	}

	private Context getContext() throws Exception {
		if (ctx != null)
			return ctx;

		Properties props = new Properties();
		props.put(Context.PROVIDER_URL, "jnp://" + host + ":1099");
		props.put(Context.INITIAL_CONTEXT_FACTORY, "org.jnp.interfaces.NamingContextFactory");
		props.put(Context.URL_PKG_PREFIXES, "org.jboss.naming:org.jnp.interfaces");
		ctx = new InitialContext(props);

		return ctx;
	}

	private DBJobTimer connectToService() throws Exception {
		if (svc != null)
			return svc;

		Context ctx = getContext();
		Object ref = ctx.lookup("DBJobTimerBean/remote");
		svc = (DBJobTimer) PortableRemoteObject.narrow(ref, DBJobTimer.class);

		return svc;
	}
	
	public void startDBJobTimer() {
		try {
			DBJobTimer svr = connectToService();
			svr.startTimer(60);
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public void stopDBJobTimer() {
		try {
			DBJobTimer svr = connectToService();
			svr.stopTimer();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public void startDBJob() {
		try {
			DBJobTimer svr = connectToService();
			svr.runDBCleanUp();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
	
	public static void main(String[] args) {
		ClimSpaceAdminClient client = new ClimSpaceAdminClient();
		String command = "start";
		
		if (args.length==0)
			command = "start";
		else
			command = args[0];
		
		if ("start".equals(command))
			client.startDBJobTimer();
		else if ("stop".equals(command))
			client.stopDBJobTimer();
		else
			client.startDBJob();
	}
}
